// 1引入Vue
import Vue from "vue";
// 2引入Vuex
import Vuex from "vuex";

import axios from "axios";
// 让Vue使用vuex插件
Vue.use(Vuex);
// 创建一个state对象
const state = {
  count: 1,
  price: 919,
  movieList: [],
};

const mutations = {
  increment(state) {
    state.count++;
  },

  incrementN(state, { n }) {
    state.count += n;
  },
  decrement(state) {
    state.count--;
  },
  setMovieList(state, movieList) {
    state.movieList = movieList;
  },
};

const actions = {
  incrementWait({ commit }) {
    setTimeout(() => {
      //我们不要在action中操作数据
      //当异步完成以后,把数据交给mutation去操作数据
      commit("increment");
    }, 2000);
  },

  incrementNWait({ commit }, payload) {
    setTimeout(() => {
      //我们不要在action中操作数据
      //当异步完成以后,把数据交给mutation去操作数据
      commit("incrementN", payload);
    }, 2000);
  },

  async getMovieList({ commit }) {
    const result = await axios.get(
      "https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=11&page_id=2&ret_num=48&session=b9fd987164f6aa47fad266f57dffaa6a"
    );
    commit("setMovieList", result.data.data.list);
  },
};

const getters = {
  myMovieList(state) {
    return state.movieList.filter((movie) => {
      return movie.albumName.length < 7 && movie.albumName.length > 3;
    });
  },
  //  //可以传参的getters
  yourMovieList(state) {
    return ({ start, end }) => {
      return state.movieList.filter((movie) => {
        return movie.albumName.length <= end && movie.albumName.length >= start;
      });
    };
  },
};
export default new Vuex.Store({
  state,
  mutations,
  getters,
  actions,
});
